package com.lisn.opengl.widget;

import android.graphics.SurfaceTexture;
import android.opengl.GLSurfaceView;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.camera.core.Preview;
import androidx.lifecycle.LifecycleOwner;

import com.lisn.opengl.filter.ScreenFilter;
import com.lisn.opengl.util.CameraXHelper;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * @author : lishan
 * @e-mail : cnlishan@163.com
 * @date : 2020/8/24 11:08 AM
 * @desc :
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class MyRender implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener, Preview.OnPreviewOutputUpdateListener {
    private MySurfaceView cameraView;
    private CameraXHelper mCameraHelper;
    //摄像头的图像
    private SurfaceTexture mCameraTexture;

    private int[] textures;
    //private int texture;
    private ScreenFilter screenFilter;
    float[] mtx = new float[16];

    public MyRender(MySurfaceView cameraView) {
        this.cameraView = cameraView;
        LifecycleOwner lifecycleOwner = (LifecycleOwner) cameraView.getContext();
        mCameraHelper = new CameraXHelper(lifecycleOwner, this);
    }

    @Override
    public void onUpdated(@NonNull Preview.PreviewOutput output) {
        //摄像头图像纹理
        mCameraTexture = output.getSurfaceTexture();
    }

    //画布创建好了
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //创建纹理ID，把摄像头与这个纹理关联
        //当做能在opengl用当一个图片ID
        //mCameraTexture.attachToGLContext(texture);

        textures = new int[1];
        mCameraTexture.attachToGLContext(textures[0]);

        //当摄像头数据有更新时回调onFrameAvailable
        mCameraTexture.setOnFrameAvailableListener(this);

        screenFilter = new ScreenFilter(cameraView.getContext());
    }

    //画布发生改变
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        screenFilter.setSize(width, height);
    }

    //开始画画
    @Override
    public void onDrawFrame(GL10 gl) {
        //更新纹理
        mCameraTexture.updateTexImage();

        mCameraTexture.getTransformMatrix(mtx);

        screenFilter.setTransformMatrix(mtx);
        screenFilter.onDraw(textures[0]);
    }

    //当有一个可用帧时调用
    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        //请求执行一次 onDrawFrame
        cameraView.requestRender();
    }


    public void onDestroy() {

    }
}
